package com.cysyz.mylib.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author Jack 使用 HttpURLConnection 来传送文件信息
 */
public class HttpURLUtil {

	/**
	 * @param strUrl		post协议传送的项目地址
	 * @param file			传送的文件（图片）	
	 * @param filename 		文件名称（图片的原来名称）
	 * @param username		用户名称（幼儿园用户的userName）
	 * @param description	图片的描述信息
	 * @param kidspostkey	相互协议的key密钥
	 * @return 文件上传之后使用IE访问的url地址
	 */
	public static String getConnection(String strUrl, File file,
			String filename, String username,
			String description, String kidspostkey, String orgid, String type) {
		String file_url = "";//定义返回值，该值为文件上传之后使用IE访问的url地址
		try {
			String BOUNDARY = "---------------------------6270582926777"; // 定义数据分隔线

			URL url = new URL(strUrl);

			URLConnection rulConnection = url.openConnection();

			HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;

			httpUrlConnection.setDoOutput(true);

			httpUrlConnection.setDoInput(true);

			httpUrlConnection.setUseCaches(false);

			httpUrlConnection.setRequestMethod("POST");

			httpUrlConnection.setRequestProperty("connection", "Keep-Alive");

			httpUrlConnection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

			httpUrlConnection.setRequestProperty("Charsert", "UTF-8");

			httpUrlConnection.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + BOUNDARY);

			OutputStream outStrm = new DataOutputStream(httpUrlConnection
					.getOutputStream());

			// 拼写用户名称
			String name = "postvo.username";
			createPostString(outStrm, BOUNDARY, name, username);
			
			name = "postvo.orgid";
			createPostString(outStrm, BOUNDARY, name, orgid);
			
			name = "postvo.type";
			createPostString(outStrm, BOUNDARY, name, type);

			// 拼写协议key
			name = "postvo.key";
			createPostString(outStrm, BOUNDARY, name, kidspostkey);

			// 拼写文件的描述
			name = "file_data.description";
			createPostString(outStrm, BOUNDARY, name, description);
			
			// 拼写文件的原名称 如：girl.jpg
			name = "fileName";
			createPostString(outStrm, BOUNDARY, name, filename);

			// 拼接传输的内容
			name = "postvo.turFile";
			createPost(outStrm, BOUNDARY, file, name, filename);

			outStrm.flush();
			outStrm.close();

			// 注意，实际发送请求的代码段就在这里
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
			
			String sCurrentLine = "";
			String sTotalString = "";
			while ((sCurrentLine = bufferedReader.readLine()) != null) {
				sTotalString += sCurrentLine;
			}
			String start = "=start=";
			String end = "=end=";
			int beginIndex = sTotalString.indexOf(start)+start.length();
			int endIndex = sTotalString.indexOf(end);
			file_url = sTotalString.substring(beginIndex, endIndex);
			System.out.println("=== sTotalString = "+file_url);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return file_url;
	}

	/**
	 * @param outStrm 写入流
	 * @param BOUNDARY 分隔符
	 * @param file	文件对象
	 * @param name 传送对象的名称
	 * @param filename 传送文件的真实名称
	 */
	private static void createPost(OutputStream outStrm, String BOUNDARY,
			File file, String name, String filename) {
		try {
			byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
			StringBuilder sb = new StringBuilder();
			sb.append("--");
			sb.append(BOUNDARY);
			sb.append("\r\n");

			sb.append("Content-Disposition: form-data; name=\"" + name
					+ "\"; filename=\"" + filename + "\"\r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");
			byte[] data = sb.toString().getBytes();
			outStrm.write(data);
			DataInputStream in = new DataInputStream(new FileInputStream(file));
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				outStrm.write(bufferOut, 0, bytes);
			}
			in.close();

			outStrm.write(end_data);

		} catch (Exception e) {

		}
	}

	/**
	 * @param outStrm 写入流
	 * @param BOUNDARY 分割符号
	 * @param name	传送东西的名称
	 * @param value	传送东西的值
	 */
	private static void createPostString(OutputStream outStrm, String BOUNDARY,
			String name, String value) {
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("--");
			sb.append(BOUNDARY);
			sb.append("\r\n");

			sb.append("Content-Disposition: form-data; name=\"" + name
					+ "\"\r\n\r\n");
			sb.append(value + "\r\n");
			byte[] data = sb.toString().getBytes();
			outStrm.write(data);

		} catch (Exception e) {

		}
	}

}
